package com.zhenhao.xsq.ui.activity.web;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.orhanobut.logger.Logger;
import com.zhenhao.xsq.R;
import com.zhenhao.xsq.application.AppConfig;
import com.zhenhao.xsq.base.BaseActivity;
import com.zhenhao.xsq.data.api.API;
import com.zhenhao.xsq.entity.EvenbugMessage;
import com.zhenhao.xsq.ui.activity.web.component.DaggerWebSatisficingComponent;
import com.zhenhao.xsq.ui.activity.web.contract.WebSatisficingContract;
import com.zhenhao.xsq.ui.activity.web.module.WebSatisficingModule;
import com.zhenhao.xsq.ui.activity.web.presenter.WebSatisficingPresenter;
import com.zhenhao.xsq.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author xlei
 * @Package com.ljcs.cxwl.ui.activity.web
 * @Description: $description
 * @date 2018/07/12 11:56:05
 */

public class WebSatisficingActivity extends BaseActivity implements WebSatisficingContract.View {

    @Inject
    WebSatisficingPresenter mPresenter;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.webView)
    WebView webView;

    private String name;
    private String address;

    public final static String WEB_NAME = "name";
    public final static String WEB_ADDRESS = "address";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_webview_sat);
        ButterKnife.bind(this);
        //        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        name = bundle.getString("name");
        toolbarTitle.setText(name);
        address = bundle.getString("address");
        Logger.i(address);
    }

    @Override
    protected void initData() {
        init();
    }

    private void init() {

        webView.getSettings().setDefaultFontSize(16);
        webView.getSettings().setSupportZoom(true);//支持缩放，默认为true
        webView.getSettings().setBuiltInZoomControls(true);//设置内置的缩放控件。若为false，则该WebView不可缩放
        webView.getSettings().setDisplayZoomControls(false);//隐藏原生的缩放控件
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);//支持通过JS打开新窗口
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);//设置缓存模式 LOAD_NO_CACHE:
        // 不使用缓存，只从网络获取数据.
        webView.getSettings().setDefaultTextEncodingName("UTF -8");//设置编码格式
        webView.getSettings().setJavaScriptEnabled(true);//与Javascript交互
        webView.getSettings().setAllowContentAccess(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setUseWideViewPort(true);//将图片调整到适合webview的大小
        webView.getSettings().setLoadWithOverviewMode(true);// 缩放至屏幕的大小
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
        }

        webView.addJavascriptInterface(new PayJavaScriptInterface(), "js");//提供关闭页面接口给h5
//        WwebView.loadUrl("javascript:callFromJava('1')");
        // 覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        webView.setWebViewClient(new WebViewClient() {
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                // 返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
//                view.loadUrl(url);
//                return true;
//            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            private String startUrl;

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
//                loadingView.show();
                startUrl = url;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (startUrl != null && startUrl.equals(url)) {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put(API.img_cookie_key, API.img_cookie_value);
                    view.loadUrl(url, map);
                } else {
                    //交给系统处理
                    return super.shouldOverrideUrlLoading(view, url);
                }
                return true;
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    // 网页加载完成
                    progressBar.setVisibility(View.GONE);
                } else {
                    // 加载中
                    if (View.GONE == progressBar.getVisibility()) {
                        progressBar.setVisibility(View.VISIBLE);
                    }
                    progressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }
        });

        Map<String, String> map = new HashMap<String, String>();
        map.put(API.img_cookie_key, API.img_cookie_value);
        // WebView加载web资源
        webView.loadUrl(address, map);

        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String file_url, String userAgent, String
                    contentDisposition, String mimeType, long contentLength) {
                Log.e("wh file_url", "" + file_url);

                downloadBySystem(file_url, contentDisposition, mimeType);

//                Intent intent = new Intent(Intent.ACTION_VIEW);
//                intent.addCategory(Intent.CATEGORY_BROWSABLE);
//                intent.setData(Uri.parse(file_url));
//                startActivity(intent);


//                Map<String, String> map = new HashMap<String, String>();
//                map.put(API.img_cookie_key, API.img_cookie_value);
//                // WebView加载web资源
//                webView.loadUrl(file_url, map);

//                if (!file_url.startsWith("https://view.officeapps.live.com/op/view.aspx?src=")
//                        && (file_url.endsWith(".doc") || file_url.endsWith(".docx")
//                        || file_url.endsWith(".xls") || file_url.endsWith(".xlsx")
//                        || file_url.endsWith(".ppt") || file_url.endsWith(".pptx"))) {
//
////如果是微软可以预览的文件类型，拼接url
//                    webView.loadUrl("https://view.officeapps.live.com/op/view.aspx?src="
//                            + file_url);
//                }else {
//                    Intent intent = new Intent(Intent.ACTION_VIEW);
//                    intent.addCategory(Intent.CATEGORY_BROWSABLE);
//                    intent.setData(Uri.parse(file_url));
//                    startActivity(intent);
//                }
            }
        });
    }

    private void downloadBySystem(String url, String contentDisposition, String mimeType) {


        // 指定下载地址
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.addRequestHeader(API.img_cookie_key, API.img_cookie_value);
        // 允许媒体扫描，根据下载的文件类型被加入相册、音乐等媒体库
        request.allowScanningByMediaScanner();
        // 设置通知的显示类型，下载进行时和完成后显示通知
        request.setNotificationVisibility(DownloadManager.Request
                .VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        // 设置通知栏的标题，如果不设置，默认使用文件名
//        request.setTitle("This is title");
        // 设置通知栏的描述
//        request.setDescription("This is description");
        // 允许在计费流量下下载
        request.setAllowedOverMetered(false);
        // 允许该记录在下载管理界面可见
        request.setVisibleInDownloadsUi(false);
        // 允许漫游时下载
        request.setAllowedOverRoaming(true);
        // 允许下载的网路类型
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        // 设置下载文件保存的路径和文件名
        String fileName = URLUtil.guessFileName(url, contentDisposition, mimeType);
        Logger.i("fileName:{}" + fileName);
        ToastUtil.showLong("正在下载文件" + fileName + "至" + Environment.DIRECTORY_DOWNLOADS);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
//        另外可选一下方法，自定义下载路径
//        request.setDestinationUri()
//        request.setDestinationInExternalFilesDir()
        final DownloadManager downloadManager = (DownloadManager) getSystemService
                (DOWNLOAD_SERVICE);
        // 添加一个下载任务
        long downloadId = downloadManager.enqueue(request);
        Logger.i("downloadId:{}" + downloadId);

        // 使用
        DownloadCompleteReceiver receiver = new DownloadCompleteReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        registerReceiver(receiver, intentFilter);
    }

    @Override
    protected void setupActivityComponent() {
        DaggerWebSatisficingComponent.builder().appComponent(((AppConfig) getApplication())
                .getApplicationComponent()
        ).webSatisficingModule(new WebSatisficingModule(this)).build().inject(this);
    }

    @Override
    public void setPresenter(WebSatisficingContract.WebSatisficingContractPresenter presenter) {
        mPresenter = (WebSatisficingPresenter) presenter;
    }

    @Override
    public void showProgressDialog() {
        progressDialog.show();
    }

    @Override
    public void closeProgressDialog() {
        progressDialog.hide();
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (webView.canGoBack()) {
//                webView.goBack();// 返回上一页面
//                return true;
//            } else {
//                finish();// 退出程序
//            }
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            if (webView.getUrl().equals(address)) {
                super.onBackPressed();
            } else {
                webView.goBack();
            }
        } else {
            super.onBackPressed();
        }
    }

    public class PayJavaScriptInterface {
        @JavascriptInterface
        public void back() {
            ToastUtil.showLong("提交成功");
            EventBus.getDefault().post(new EvenbugMessage(EvenbugMessage.MSG_WJDC_REFRESH));
            finish();
        }
    }

    private class DownloadCompleteReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("onReceive. intent:{}", intent != null ? intent.toUri(0) : null);
            if (intent != null) {
                if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
                    long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                    Log.e("downloadId:{}", "" + downloadId);
                    DownloadManager downloadManager =
                            (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
                    String type = downloadManager.getMimeTypeForDownloadedFile(downloadId);
                    Log.e("wh file_url", "getMimeTypeForDownloadedFile:{}" + type);
                    if (TextUtils.isEmpty(type)) {
                        type = "*/*";
                    }
                    Uri uri = downloadManager.getUriForDownloadedFile(downloadId);
                    Log.e("UriForDownloadedFile:{}", "" + uri);
                    if (uri != null) {
//                        Intent handlerIntent = new Intent(Intent.ACTION_VIEW);
//                        handlerIntent.setDataAndType(uri, type);
//                        context.startActivity(handlerIntent);
                        ToastUtil.showLong("下载完毕");
                        finish();
                    }
                }
            }
            context.unregisterReceiver(this);
        }
    }
}